import math

class PhysicsObject:
    def __init__(self, x, y, radius=15):
        self.x = x
        self.y = y
        self.radius = radius
        self.velocity_x = 0
        self.velocity_y = 0
        self.is_flying = False
        
        # 物理常量
        self.gravity = 0.5
        self.elasticity = 0.7  # 弹性系数
        self.drag = 0.99  # 空气阻力

    def launch(self, start_x, start_y, pull_x, pull_y):
        """根据拉动距离计算初始速度"""
        self.x = start_x
        self.y = start_y
        
        # 计算发射速度（与拉动距离成正比）
        dx = start_x - pull_x
        dy = start_y - pull_y
        distance = math.sqrt(dx * dx + dy * dy)
        
        # 速度与拉动距离成正比，但有最大限制
        power = min(distance * 0.15, 20)
        
        # 设置初始速度
        self.velocity_x = dx * power / distance
        self.velocity_y = dy * power / distance
        self.is_flying = True

    def update(self):
        """更新物体位置和速度"""
        if not self.is_flying:
            return

        # 应用重力
        self.velocity_y += self.gravity
        
        # 应用空气阻力
        self.velocity_x *= self.drag
        self.velocity_y *= self.drag
        
        # 更新位置
        self.x += self.velocity_x
        self.y += self.velocity_y

    def check_collision(self, rect):
        """检查与矩形的碰撞"""
        # 获取圆心到矩形的最近点
        closest_x = max(rect.left, min(self.x, rect.right))
        closest_y = max(rect.top, min(self.y, rect.bottom))
        
        # 计算圆心到最近点的距离
        distance_x = self.x - closest_x
        distance_y = self.y - closest_y
        distance = math.sqrt(distance_x * distance_x + distance_y * distance_y)
        
        # 如果距离小于圆的半径，发生碰撞
        return distance <= self.radius

    def handle_boundary_collision(self, width, height):
        """处理与边界的碰撞"""
        # 左右边界
        if self.x - self.radius < 0:
            self.x = self.radius
            self.velocity_x = -self.velocity_x * self.elasticity
        elif self.x + self.radius > width:
            self.x = width - self.radius
            self.velocity_x = -self.velocity_x * self.elasticity
        
        # 上下边界
        if self.y - self.radius < 0:
            self.y = self.radius
            self.velocity_y = -self.velocity_y * self.elasticity
        elif self.y + self.radius > height:
            self.y = height - self.radius
            self.velocity_y = -self.velocity_y * self.elasticity
            # 地面摩擦
            self.velocity_x *= 0.95